<template>
  <view class="container">
    <view class="header">
      <view class="back-btn" @tap="goBack">
        <text class="iconfont icon-back"></text>
      </view>
      <text class="title">{{ isFaceRegistration ? '人脸识别录入' : '人脸识别登录' }}</text>
    </view>
    
    <view class="face-scan">
      <view class="scan-area" :class="{ scanning: isScanning, recognized: isRecognized, failed: isFaceFailed }">
        <!-- 摄像头视图组件 -->
        <camera v-if="isScanning && !isRecognized" device-position="front" flash="off" class="camera" @error="handleCameraError"></camera>
        
        <view class="scan-frame">
          <view class="corner top-left"></view>
          <view class="corner top-right"></view>
          <view class="corner bottom-left"></view>
          <view class="corner bottom-right"></view>
          
          <view class="scan-line" v-if="isScanning"></view>
          <view class="face-avatar" v-if="isRecognized || isFaceFailed">
            <image :src="faceImage || '/static/images/avatar.gif'"></image>
          </view>
        </view>
        
        <text class="scan-tips">{{ scanTips }}</text>
      </view>
      
      <view class="action-btns">
        <button class="action-btn primary" @tap="startScan" v-if="!isScanning && !isRecognized && !isFaceFailed">
          开始扫描
        </button>
        <button class="action-btn primary" @tap="takePhoto" v-if="isScanning && !isRecognized">
          拍照
        </button>
        <button class="action-btn cancel" @tap="cancelScan" v-if="isScanning">
          取消
        </button>
        <button class="action-btn primary" @tap="confirmFaceAction" v-if="isRecognized">
          {{ isFaceRegistration ? '确认录入' : '确认登录' }}
        </button>
        <button class="action-btn retry" @tap="retryCapture" v-if="isFaceFailed || isRecognized">
          重新拍照
        </button>
      </view>
      
      <view class="tips">
        <text>{{ isFaceRegistration ? '录入人脸信息，下次可直接登录' : '请确保光线充足，面部无遮挡' }}</text>
        <text>面部需清晰可见，不要佩戴墨镜等饰品</text>
      </view>
      
      <view class="switch-mode" @tap="switchMode">
        <text>{{ isFaceRegistration ? '已有人脸信息？点此登录' : '首次使用？点此录入人脸' }}</text>
      </view>
    </view>
  </view>
</template>

<script>
import request from '@/utils/request'
import { BASE_URL, SERVICE_PREFIX } from '@/utils/request'

export default {
  data() {
    return {
      isScanning: false,
      isRecognized: false,
      isFaceFailed: false,  // 是否人脸录入失败
      isFaceRegistration: false,  // 是否为人脸录入模式
      scanTips: '请将脸部放入框内',
      faceImage: '',
      scanTimeout: null,
      cameraContext: null
    }
  },
  onLoad(options) {
    // 检查是否是人脸录入模式
    if (options.mode === 'register') {
      this.isFaceRegistration = true;
    }
    
    // 创建相机上下文
    this.cameraContext = uni.createCameraContext();
  },
  onUnload() {
    // 清除定时器
    if (this.scanTimeout) {
      clearTimeout(this.scanTimeout);
    }
  },
  methods: {
    goBack() {
      uni.navigateBack();
    },
    
    switchMode() {
      this.isFaceRegistration = !this.isFaceRegistration;
      this.isScanning = false;
      this.isRecognized = false;
      this.isFaceFailed = false;
      this.faceImage = '';
      this.scanTips = '请将脸部放入框内';
    },
    
    startScan() {
      // 请求摄像头权限
      uni.authorize({
        scope: 'scope.camera',
        success: () => {
          this.isScanning = true;
          this.scanTips = '请对准人脸，点击拍照按钮';
        },
        fail: () => {
          uni.showModal({
            title: '提示',
            content: '您拒绝了摄像头权限，无法进行人脸识别',
            showCancel: false
          });
        }
      });
    },
    
    takePhoto() {
      if (!this.cameraContext) {
        this.cameraContext = uni.createCameraContext();
      }
      
      this.scanTips = '拍照中...';
      
      // 调用摄像头拍照
      this.cameraContext.takePhoto({
        quality: 'high',
        success: (res) => {
          // 拍照成功，获取图片路径
          this.faceImage = res.tempImagePath;
          
          // 标记为识别成功状态
          this.isScanning = false;
          this.isRecognized = true;
          this.isFaceFailed = false;
          this.scanTips = this.isFaceRegistration ? '人脸捕获成功' : '人脸捕获成功';
          
          uni.showToast({
            title: '拍照成功',
            icon: 'success'
          });
        },
        fail: (err) => {
          console.error('拍照失败:', err);
          
          uni.showToast({
            title: '拍照失败，请重试',
            icon: 'none'
          });
        }
      });
    },
    
    // 重新拍照功能
    retryCapture() {
      this.isRecognized = false;
      this.isFaceFailed = false;
      this.faceImage = '';
      this.scanTips = '请对准人脸重新拍照';
      this.startScan();
    },
    
    handleCameraError(e) {
      console.error('相机错误:', e);
      this.cancelScan();
      
      uni.showModal({
        title: '相机错误',
        content: '无法启动相机，请检查权限或重试',
        showCancel: false
      });
    },
    
    cancelScan() {
      if (this.scanTimeout) {
        clearTimeout(this.scanTimeout);
      }
      
      this.isScanning = false;
      this.scanTips = '请将脸部放入框内';
    },
    
    confirmFaceAction() {
      if (!this.faceImage) {
        uni.showToast({
          title: '请先拍摄人脸照片',
          icon: 'none'
        });
        return;
      }
      
      // 根据当前模式决定调用的接口
      if (this.isFaceRegistration) {
        this.uploadFace();
      } else {
        this.faceLogin();
      }
    },
    
    // 人脸录入
    uploadFace() {
      uni.showLoading({
        title: '正在录入人脸数据...'
      });
      
      console.log('开始上传人脸数据，图片路径:', this.faceImage);
      const uploadUrl = BASE_URL + SERVICE_PREFIX.LOGIN + '/api/user/uploadFace';
      console.log('上传URL:', uploadUrl);
      
      // 修复URL问题，使用正确的BASE_URL和SERVICE_PREFIX配置
      uni.uploadFile({
        url: uploadUrl,
        filePath: this.faceImage,
        name: 'faceImage',
        formData: {
          userId: uni.getStorageSync('userInfo')?.userId || ''
        },
        header: {
          'Authorization': uni.getStorageSync('token') ? `Bearer ${uni.getStorageSync('token')}` : '',
          'Content-Type': 'multipart/form-data'
        },
        success: (uploadRes) => {
          console.log('人脸录入响应:', uploadRes);
          uni.hideLoading();
          
          // 解析返回结果
          let result;
          try {
            result = JSON.parse(uploadRes.data);
          } catch (e) {
            console.error('解析响应数据失败:', e, uploadRes.data);
            result = { code: 500, message: '服务器返回的数据格式错误' };
          }
          
          if (result.code === 200) {
            uni.showToast({
              title: '人脸录入成功',
              icon: 'success'
            });
            
            // 延迟跳转回登录页
            setTimeout(() => {
              uni.navigateBack();
            }, 1500);
          } else {
            // 标记为失败状态
            this.isRecognized = false;
            this.isFaceFailed = true;
            this.scanTips = result.errorMessage || '人脸录入失败，请重试';
            
            uni.showToast({
              title: result.errorMessage || '人脸录入失败',
              icon: 'none'
            });
          }
        },
        fail: (err) => {
          console.error('人脸录入失败:', err);
          uni.hideLoading();
          
          // 标记为失败状态
          this.isRecognized = false;
          this.isFaceFailed = true;
          this.scanTips = '人脸录入失败，请重试';
          
          // 显示详细错误信息便于调试
          let errorMsg = '人脸录入失败，请重试';
          if (err.errMsg) {
            errorMsg += '\n错误信息: ' + err.errMsg;
          }
          
          uni.showToast({
            title: errorMsg,
            icon: 'none',
            duration: 3000
          });
        }
      });
    },
    
    // 人脸登录
    faceLogin() {
      uni.showLoading({
        title: '正在验证人脸...'
      });
      
      console.log('开始人脸登录，图片路径:', this.faceImage);
      const loginUrl = BASE_URL + SERVICE_PREFIX.LOGIN + '/api/user/faceLogin';
      console.log('登录URL:', loginUrl);
      
      // 修复URL问题，使用正确的BASE_URL和SERVICE_PREFIX配置
      uni.uploadFile({
        url: loginUrl,
        filePath: this.faceImage,
        name: 'faceImage',
        header: {
          'Content-Type': 'multipart/form-data'
        },
        success: (uploadRes) => {
          console.log('人脸登录响应:', uploadRes);
          uni.hideLoading();
          
          // 解析返回结果
          let result;
          try {
            result = JSON.parse(uploadRes.data);
          } catch (e) {
            console.error('解析响应数据失败:', e, uploadRes.data);
            result = { code: 500, message: '服务器返回的数据格式错误' };
          }
          
          if (result.code === 200) {
            // 清除游客模式
            uni.removeStorageSync('isGuest');
            
            // 保存登录信息
            if (result.data) {
              uni.setStorageSync('token', result.data.token || result.data);
              uni.setStorageSync('userInfo', result.data);
            }
            
            uni.showToast({
              title:  result.errorMessage||'识别成功,登录中...',
              icon: 'success'
            });
            
            // 延迟跳转到首页
            setTimeout(() => {
              uni.switchTab({
                url: '/pages/index/index'
              });
            }, 1500);
          } else {
            // 标记为失败状态
            this.isRecognized = false;
            this.isFaceFailed = true;
            this.scanTips = result.errorMessage || '人脸识别失败，请重试';
            
            uni.showToast({
              title: result.errorMessage || '人脸识别失败',
              icon: 'none'
            });
          }
        },
        fail: (err) => {
          console.error('人脸识别登录失败:', err);
          uni.hideLoading();
          
          // 标记为失败状态
          this.isRecognized = false;
          this.isFaceFailed = true;
          this.scanTips = '人脸识别失败，请重试';
          
          // 显示详细错误信息便于调试
          let errorMsg = '人脸识别登录失败，请重试';
          if (err.errMsg) {
            errorMsg += '\n错误信息: ' + err.errMsg;
          }
          
          uni.showToast({
            title: errorMsg,
            icon: 'none',
            duration: 3000
          });
        }
      });
    }
  }
}
</script>

<style lang="scss">
.container {
  min-height: 100vh;
  background: #fff;
  display: flex;
  flex-direction: column;
}

.header {
  display: flex;
  align-items: center;
  height: 100rpx;
  padding: 0 30rpx;
  position: relative;
  
  .back-btn {
    width: 80rpx;
    height: 80rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    
    .iconfont {
      font-size: 40rpx;
      color: #333;
    }
  }
  
  .title {
    position: absolute;
    left: 0;
    right: 0;
    text-align: center;
    font-size: 36rpx;
    font-weight: bold;
    color: #333;
  }
}

.face-scan {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40rpx;
  
  .scan-area {
    margin-bottom: 60rpx;
    position: relative;
    
    .camera {
      width: 500rpx;
      height: 600rpx;
      position: absolute;
      top: 0;
      left: 0;
      z-index: 1;
    }
    
    .scan-frame {
      width: 500rpx;
      height: 600rpx;
      position: relative;
      margin-bottom: 30rpx;
      z-index: 2;
      
      .corner {
        position: absolute;
        width: 50rpx;
        height: 50rpx;
        border-color: #4080ff;
        border-style: solid;
        border-width: 0;
        
        &.top-left {
          top: 0;
          left: 0;
          border-top-width: 6rpx;
          border-left-width: 6rpx;
        }
        
        &.top-right {
          top: 0;
          right: 0;
          border-top-width: 6rpx;
          border-right-width: 6rpx;
        }
        
        &.bottom-left {
          bottom: 0;
          left: 0;
          border-bottom-width: 6rpx;
          border-left-width: 6rpx;
        }
        
        &.bottom-right {
          bottom: 0;
          right: 0;
          border-bottom-width: 6rpx;
          border-right-width: 6rpx;
        }
      }
      
      .scan-line {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 4rpx;
        background: linear-gradient(to right, transparent, #4080ff, transparent);
        animation: scanAnimation 2s linear infinite;
      }
      
      .face-avatar {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        width: 240rpx;
        height: 240rpx;
        border-radius: 50%;
        overflow: hidden;
        border: 6rpx solid #4080ff;
        
        image {
          width: 100%;
          height: 100%;
          object-fit: cover;
        }
      }
    }
    
    .scan-tips {
      display: block;
      text-align: center;
      font-size: 32rpx;
      color: #333;
      z-index: 3;
      position: relative;
    }
    
    &.scanning {
      .scan-frame {
        .corner {
          border-color: #ffb74d;
        }
        
        .scan-line {
          background: linear-gradient(to right, transparent, #ffb74d, transparent);
        }
      }
      
      .scan-tips {
        color: #ffb74d;
      }
    }
    
    &.recognized {
      .scan-frame {
        .corner {
          border-color: #4caf50;
        }
        
        .face-avatar {
          border-color: #4caf50;
        }
      }
      
      .scan-tips {
        color: #4caf50;
      }
    }
    
    &.failed {
      .scan-frame {
        .corner {
          border-color: #f44336;
        }
        
        .face-avatar {
          border-color: #f44336;
        }
      }
      
      .scan-tips {
        color: #f44336;
      }
    }
  }
  
  .action-btns {
    margin-bottom: 60rpx;
    display: flex;
    flex-wrap: wrap;
    justify-content: center;
    
    .action-btn {
      width: 300rpx;
      height: 80rpx;
      line-height: 80rpx;
      font-size: 32rpx;
      border-radius: 40rpx;
      margin: 10rpx 20rpx;
      
      &.primary {
        background: #4080ff;
        color: #fff;
      }
      
      &.cancel {
        background: #f5f5f5;
        color: #666;
      }
      
      &.retry {
        background: #ff9800;
        color: #fff;
      }
    }
  }
  
  .tips {
    text-align: center;
    margin-bottom: 40rpx;
    
    text {
      display: block;
      font-size: 28rpx;
      color: #999;
      line-height: 1.8;
    }
  }
  
  .switch-mode {
    text-align: center;
    
    text {
      font-size: 28rpx;
      color: #4080ff;
      text-decoration: underline;
    }
  }
}

@keyframes scanAnimation {
  0% {
    top: 0;
  }
  50% {
    top: 100%;
  }
  100% {
    top: 0;
  }
}
</style> 